import { getFileList } from "@/lib/api/fileController";
import { useCallback, useEffect, useRef, useState } from "react";
import { Table, type TableProps } from "antd";
import { formatDate } from "@/lib/util/datetime";
import { formatFileSize } from "@/lib/util/unit";
import { FileIcon } from "./FileIcon";

import "./TableFilePlan.css";
import PreviewFile from "./PreviewFile";
import { BsFileEarmark } from "react-icons/bs";
import type { FileInfo } from "@/lib/api/types";
import { useNavigate } from "react-router-dom";
import { useStore } from "@/layout/RootLayout";

type TableFilePlanProps = {
  direct_path: string;
};

const columns: TableProps<FileInfo>["columns"] = [
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    render: (text: string, record: FileInfo) => {
      return <><FileIcon is_dir={record.isDir} />{text}</>
    }
  },
  {
    title: "修改时间",
    dataIndex: "modTime",
    key: "modTime",
    render: (modTime: string) => {
      const datetime = new Date(modTime.replace(/(\.\d{3})\d+/, "$1"));
      const text = formatDate(datetime);
      return <>{text}</>
    }
  },
  {
    title: "大小",
    dataIndex: "size",
    key: "size",
    render: (size) => {
      const text = formatFileSize(size, true);
      return <>{text}</>
    }
  }
]

export default function TableFilePlan({ direct_path }: TableFilePlanProps) {
  const [fileList, setFileList] = useState<FileInfo[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const [selectBox, setSelectBox] = useState<null | { x: number; y: number; w: number; h: number }>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [previewFile, setPreviewFile] = useState<{ path: string; name: string; } | null>(null);

  const { items, setItems } = useStore()

  const navigate = useNavigate();

  useEffect(() => {
    getFileList({ dir: direct_path }).then(res => {
      setFileList(res.fileList);
    }).catch(console.error);

    if (containerRef) {
      containerRef.current?.addEventListener("mousedown", onMouseDown);
    }

    return () => {
      if (containerRef) {
        containerRef.current?.removeEventListener("mousedown", onMouseDown);
      }
    }

  }, [direct_path]);


  const onMouseDown = useCallback((e: MouseEvent) => {

    if (e.button !== 0) return; // 只允许左键
    const startX = e.clientX;
    const startY = e.clientY;

    const container = containerRef.current;
    if (!container) return;
    const containerRect = container.getBoundingClientRect();

    const onMouseMove = (e: MouseEvent) => {
      let x = Math.min(e.clientX, startX);
      let y = Math.min(e.clientY, startY);
      let w = Math.abs(e.clientX - startX);
      let h = Math.abs(e.clientY - startY);

      // 限制在 container 内
      if (x < containerRect.left) {
        w -= containerRect.left - x;
        x = containerRect.left;
      }
      if (y < containerRect.top) {
        h -= containerRect.top - y;
        y = containerRect.top;
      }
      if (x + w > containerRect.right) {
        w = containerRect.right - x;
      }
      if (y + h > containerRect.bottom) {
        h = containerRect.bottom - y;
      }


      setSelectBox({ x, y, w, h });

      // 判断每行是否在框内
      const container = containerRef.current;
      if (!container) return;
      const rows = container.querySelectorAll<HTMLTableRowElement>(".ant-table-row");
      const selected: string[] = [];
      rows.forEach((row) => {
        const rect = row.getBoundingClientRect();
        if (
          rect.left < x + w &&
          rect.right > x &&
          rect.top < y + h &&
          rect.bottom > y
        ) {
          selected.push(row.dataset.rowKey!);
        }
      });
      setSelectedRowKeys(selected);
    };

    const onMouseUp = () => {
      setSelectBox(null);
      window.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("mouseup", onMouseUp);
    };

    window.addEventListener("mousemove", onMouseMove);
    window.addEventListener("mouseup", onMouseUp);
  }, [])

  return (
    <div
      className="min-h-screen relative select-none bg-gray-100 pb-8 dark:bg-gray-900"
      ref={containerRef}
    // onMouseDown={onMouseDown}
    >
      <Table<FileInfo>
        columns={columns}
        dataSource={fileList}
        rowKey="name"
        rowClassName={(record) =>
          selectedRowKeys.includes(record.name) ? "drag-selected" : ""
        }
        onRow={(record, index) => ({
          onClick: () => {
            const selected: string[] = [
              record.name,
            ]
            setSelectedRowKeys(selected)
          },
          onDoubleClick: () => {
            if (record.isDir) {
              navigate("/?path=" + encodeURIComponent(direct_path + "/" + record.name))
            } else {
              setPreviewFile({ path: direct_path + "/" + record.name, name: record.name });
              containerRef.current?.removeEventListener("mousedown", onMouseDown)
            }
          }
        })}
        pagination={false}
        size="small"
        locale={{ emptyText: "文件夹为空" }}
      />

      {selectBox && (
        <div
          className="fixed z-10"
          style={{
            top: selectBox.y,
            left: selectBox.x,
            width: selectBox.w,
            height: selectBox.h,
            background: "rgba(24,144,255,0.2)",
            border: "1px solid #1890ff",
            pointerEvents: "none",
          }}
        />
      )}

      {/* 文件预览弹窗 */}
      {previewFile && (
        <PreviewFile
          filePath={previewFile.path}
          setPreviewFile={setPreviewFile}
        />
      )}
    </div>
  );
}

